package com.codebattery.service;


import com.codebattery.client.OrderFeignClient;
import com.codebattery.domain.entity.Member;
import com.codebattery.domain.model.MemberOrderInfo;
import com.codebattery.domain.model.UserLoginInfo;
import com.codebattery.repository.BaseRepository;
import com.codebattery.repository.MemberRepository;
import com.codebattery.util.TokenUtils;
import com.nimbusds.jose.JOSEException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;


@Service
public class MemberService extends BaseService<Member, Long>{
    private static final Logger LOGGER = LoggerFactory.getLogger(MemberService.class);

    @Resource
    private MemberRepository repository;
    @Resource
    private OrderFeignClient orderFeignClient;

    @Value("${tokenSecureKey}")
    private String tokenSecureKey;

    /**
     * 创建用户
     *
     * @param member
     */
    public void createMember(Member member){
        repository.save(member);
    }

    /**
     * 注册用户
     *
     * @param member
     */
    public void register(Member member){

    }

    /**
     * 用户登录
     *
     * @param request
     */
    public UserLoginInfo login(HttpServletRequest request, String mobile, String password) throws JOSEException {
        HttpSession session = request.getSession();
        UserLoginInfo userLoginInfo = new UserLoginInfo();

        /*
         * 验证用户信息
         */
        Optional<Member> memberOptional = repository.findOne((root, query, cb) -> {
            return cb.equal(root.get("phone"), mobile);
        });

        if(memberOptional.isPresent()){
            Member member = memberOptional.get();

            /*
             * 校验密码
             */
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            if(encoder.matches(password, member.getPassword())){
                userLoginInfo.setStatus(true);
                userLoginInfo.setUserId(member.getId().toString());
                userLoginInfo.setMobile(member.getPhone());
                userLoginInfo.setUserName(member.getUsername());

                Map<String, Object> strObjectMap = new HashMap<>();
                strObjectMap.put("mobile", member.getPhone());
                strObjectMap.put("password", password);
                String tokenHS256 = TokenUtils.creatTokenHS256(strObjectMap, tokenSecureKey);   //生成token
                userLoginInfo.setToken(tokenHS256);
                session.setAttribute("userInfo", userLoginInfo); //session保存到redis
            } else {
                userLoginInfo.setStatus(false);
            }

        }




        return userLoginInfo;
    }


    @Override
    public BaseRepository<Member, Long> repository() {
        return repository;
    }

    /**
     * 查找用户订单
     *
     * @param memberId
     * @return
     */
    public Page<MemberOrderInfo> getMemeberOrders(String memberId){
        Page<MemberOrderInfo> memberOrders = orderFeignClient.getMemberOrders(memberId);
        return memberOrders;
    }
}
